<template>
  <a-modal :title="title" v-model:open="modelVisible" :width="500" :destroyOnClose="true" @ok="handleOk"
    @cancel="handleCancel" :keyboard="true" :maskClosable="true">
    <a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
      class="warning-form" @keydown.esc="handleCancel">
      <a-form-item label="仓库名称" name="warehouse" required>
        <a-select v-model:value="formData.warehouse" show-search placeholder="请输入仓库名称" :filter-option="false"
          :loading="warehouseLoading" @search="handleWarehouseSearch" @change="handleWarehouseChange"
          style="width: 100%">
          <a-select-option v-for="item in warehouseOptions" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="商品条码" name="code" required>
        <a-input v-model:value="formData.code" placeholder="请输入商品条码" :disabled="!formData.warehouse" />
      </a-form-item>
      <a-form-item label="商品名称" name="name" required>
        <a-select v-model:value="formData.name" show-search placeholder="请输入商品名称" :filter-option="false"
          :loading="productLoading" @search="handleProductSearch" @change="handleProductChange"
          :disabled="!formData.warehouse" style="width: 100%">
          <a-select-option v-for="item in productOptions" :key="item.id" :value="item.name">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="现有库存" name="currentStock">
        <a-input-number v-model:value="formData.currentStock" :min="0" :disabled="!formData.warehouse" />
      </a-form-item>
      <a-form-item label="警戒库存" name="warningStock" required>
        <a-input-number v-model:value="formData.warningStock" :min="0" :max="9999" :precision="0"
          :disabled="!formData.warehouse" placeholder="请输入0-9999之间的整数" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watch, nextTick } from 'vue';
import { FormInstance, Modal } from 'ant-design-vue';
import { useMessage } from '@/hooks/web/useMessage';
import { debounce } from '@/utils';
import { baseDataProductApi } from '/@/api/base-data/product/bom-product';
import { sendStockWarningNotice } from '@/api/base-data/store-center';


interface WarningData {
  id?: string;
  code: string;
  name: string;
  warehouse: string;
  warehouseName: string;
  currentStock?: number;
  warningStock?: number;
}

export default defineComponent({
  name: 'WarningDialog',
  components: {
    [Modal.name]: Modal,
  },
  props: {
    id: {
      type: String,
      default: '',
    },
    visible: {
      type: Boolean,
      default: false,
    },
    currentRow: {
      type: Object as () => WarningData,
      default: () => ({
        code: '',
        name: '',
        warehouse: '',
        warehouseName: '',
        currentStock: undefined,
        warningStock: undefined,
      }),
    },
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const { createMessage } = useMessage();
    const formRef = ref<FormInstance>();
    const formData = ref<WarningData>({
      code: '',
      name: '',
      warehouse: "",
      warehouseName: '',
      currentStock: undefined,
      warningStock: undefined,
    });

    const formRules = {
      code: [{ required: true, message: '请输入商品条码' }],
      name: [{ required: true, message: '请输入商品名称' }],
      warehouse: [{ required: true, message: '请输入仓库名称' }],
      currentStock: [{ required: true, message: '请输入现有库存' }],
      warningStock: [
        { required: true, message: '请输入警戒库存' },
        {
          validator: (_, value) => {
            if (value === undefined || value === null) return Promise.resolve();
            const num = Number(value);
            if (isNaN(num) || num < 0 || num > 9999 || !Number.isInteger(num)) {
              return Promise.reject('请输入0-9999之间的整数');
            }
            return Promise.resolve();
          }
        }
      ],
    };

    const warehouseLoading = ref(false);
    const warehouseOptions = ref<any[]>([]);

    const productLoading = ref(false);
    const productOptions = ref<any[]>([]);
    const currentProducts = ref<any[]>([]);

    const modelVisible = computed({
      get: () => props.visible,
      set: (val) => emit('update:visible', val),
    });

    const isEdit = computed(() => !!props.id);
    const title = computed(() => (isEdit.value ? '修改库存预警' : '新增库存预警'));

    const handleWarehouseSearch = (value: string) => {
      if (!value) {
        warehouseOptions.value = [];
        return;
      }

      warehouseLoading.value = true;
      selector({
        name: value,
        available: true
      })
        .then((res) => {
          warehouseOptions.value = res.data?.records || [];
        })
        .finally(() => {
          warehouseLoading.value = false;
        });
    };

    const debouncedSearch = debounce(handleWarehouseSearch, 300);

    const handleWarehouseChange = (value: string, option: any) => {
      if (value) {
        formData.value.warehouseName = option?.children;
      } else {
        formData.value = {
          ...formData.value,
          warehouse: '',
          warehouseName: '',
          code: '',
          name: '',
          currentStock: undefined,
          warningStock: undefined,
        };
      }
    };

    const handleOk = async () => {
      try {
        await formRef.value?.validate();
        const selectedProduct = currentProducts.value.find(item => item.name === formData.value.name);
        if (selectedProduct) {
          await checkAndSendWarning(selectedProduct);
        }
        emit('success', formData.value);
        emit('update:visible', false);
        createMessage.success(props.id ? '修改成功' : '新增成功');
      } catch (error) {
        createMessage.error('表单验证失败');
      }
    };

    const handleCancel = () => {
      emit('update:visible', false);
      nextTick(() => {
        formRef.value?.resetFields();
      });
    };

    const resetForm = () => {
      formData.value = {
        code: '',
        name: '',
        warehouse: '',
        warehouseName: '',
        currentStock: undefined,
        warningStock: undefined,
      };
      nextTick(() => {
        formRef.value?.resetFields();
      });
    };

    const handleProductSearch = (value: string) => {
      if (!value || !formData.value.warehouse) {
        productOptions.value = [];
        return;
      }

      productLoading.value = true;
      baseDataProductApi.query({
        name: value,
        scId: formData.value.warehouse,
      })
        .then((res) => {
          if (res.data?.records) {
            currentProducts.value = res.data.records;
            productOptions.value = res.data.records.map(item => ({
              id: item.id,
              name: item.name,
            }));
          }
        })
        .finally(() => {
          productLoading.value = false;
        });
    };

    const handleProductChange = (value: string) => {
      if (!value) {
        formData.value.code = '';
        formData.value.currentStock = undefined;
        return;
      }

      const selectedProduct = currentProducts.value.find(item => item.name === value);
      if (selectedProduct) {
        formData.value.code = selectedProduct.code;
        formData.value.currentStock = selectedProduct.stockNum;
        checkAndSendWarning(selectedProduct);
      }
    };

    const checkAndSendWarning = async (product: any) => {
      if (!formData.value.warningStock || !formData.value.currentStock) return;

      if (formData.value.currentStock <= formData.value.warningStock) {
        try {
          await sendStockWarningNotice({
            scId: formData.value.warehouse,
            scName: formData.value.warehouseName,
            productCode: product.code,
            productName: product.name,
            currentStock: formData.value.currentStock,
            warningStock: formData.value.warningStock,
            changeType: 'INIT'
          });
          createMessage.success('已发送库存警戒通知');
        } catch (error) {
          createMessage.error('发送库存警戒通知失败');
        }
      }
    };

    watch(
      () => props.visible,
      (newVal) => {
        if (newVal) {
          if (props.id) {
            Object.keys(formData.value).forEach(key => {
              if (props.currentRow && key in props.currentRow) {
                formData.value[key] = props.currentRow[key];
              }
            });
          } else {
            resetForm();
          }
        }
      },
      { immediate: true }
    );

    watch(
      () => props.visible,
      (newVisible) => {
        if (newVisible) {
          nextTick(() => {
            const firstInput = document.querySelector('.warning-form input');
            firstInput?.focus();
          });
        }
      }
    );

    return {
      formRef,
      formData,
      formRules,
      modelVisible,
      title,
      isEdit,
      handleOk,
      handleCancel,
      warehouseLoading,
      warehouseOptions,
      handleWarehouseSearch: debouncedSearch,
      handleWarehouseChange,
      productLoading,
      productOptions,
      handleProductSearch,
      handleProductChange,
    };
  },
});
</script>

<style lang="less" scoped>
.warning-form {
  padding: 24px 16px;

  :deep(.ant-form-item) {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    .ant-form-item-label {
      text-align: right;
      padding-right: 8px;
    }

    .ant-select,
    .ant-input,
    .ant-input-number {
      width: 100%;
    }
  }
}
</style>
